package com.sjc.designpattern.factory;

/**
 * @Classname FactoryMethodPatternDemo
 * @Description 工厂方法模式：模板方法模式+简单工厂模式
 * 面向接口编程 + 抽取相同方法到父类
 * @Date 2020/4/25 10:22
 * @Created by SangJiacun
 */
public class FactoryMethodPatternDemo {
    public static void main(String[] args) {
        Product product1 = Product1Factory.get().createProduct();
        product1.execute();

        Product product2 = Product2Factory.get().createProduct();
        product2.execute();

//        场景：
//        1. 我们现在要生产的产品有多种
//        2. 每种产品的生产过程，都有一些是共同的逻辑，但是也有一些是特殊的逻辑
//        3. 现在要生产出来各种产品
    }

    public interface Product {
        void execute();
    }

    public static class Product1 implements Product {
        @Override
        public void execute() {
            System.out.println("产品1的功能逻辑");
        }
    }

    public static class Product2 implements Product {
        @Override
        public void execute() {
            System.out.println("产品2的功能逻辑");
        }
    }

    //抽象工厂
    public static abstract class AbstractProductFactory {
        public Product createProduct() {
            commonCreate();
            return specificCreate();
        }
        private void commonCreate() {
            System.out.println("生产产品的通用逻辑，修改");
        }
        protected abstract Product specificCreate();
    }

    public static class Product1Factory extends AbstractProductFactory {

        private static final Product1Factory instance = new Product1Factory();

        private Product1Factory() {
        }

        public static Product1Factory get() {
            return instance;
        }

        @Override
        public Product specificCreate() {
            System.out.println("生产产品1的特殊逻辑");
            return new Product1();
        }
    }

    public static class Product2Factory extends AbstractProductFactory {

        private static final Product2Factory instance = new Product2Factory();

        private Product2Factory() {

        }

        public static Product2Factory get() {
            return instance;
        }

        @Override
        public Product specificCreate() {
            System.out.println("生产产品2的特殊逻辑");
            return new Product2();
        }
    }

}
